package com.example.service;

import com.example.model.LearningPath;
import com.example.model.Question;
import com.example.repository.LearningPathRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.PageRequest;

import java.time.LocalDateTime;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class LearningService {
    
    @Autowired
    private OpenAiService openAiService;
    
    @Autowired
    private QuestionService questionService;
    
    @Autowired
    private LearningPathRepository learningPathRepository;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    public Map<String, Object> analyzeResume(String resumeContent) {
        try {
            List<String> analysisResult = openAiService.analyzeResume(resumeContent);
            Map<String, Object> result = new HashMap<>();
            result.put("topics", analysisResult);
            return result;
        } catch (Exception e) {
            throw new RuntimeException("简历分析失败", e);
        }
    }
    
    public LearningPath createLearningPath(String topic) {
        String content = openAiService.generateLearningPath(topic);
        
        LearningPath path = new LearningPath();
        path.setTopic(topic);
        path.setContent(content);
        path.setCreateTime(LocalDateTime.now());
        
        // 生成相关练习题
        List<Question> questions = generateQuestionsForTopic(topic);
        path.setQuestions(questions);
        
        return learningPathRepository.save(path);
    }
    
    private List<Question> generateQuestionsForTopic(String topic) {
        try {
            // 为每个主题生成5个相关问题
            List<Question> questions = questionService.generateQuestionsForTopic(topic, 5);
            questions.forEach(q -> q.setCreateTime(LocalDateTime.now()));
            return questions;
        } catch (Exception e) {
            throw new RuntimeException("生成练习题失败", e);
        }
    }
    
    public String getInterviewFeedback(Long questionId) {
        Question question = questionService.findById(questionId);
        return openAiService.getInterviewFeedback(question.getQuestion(), question.getAnswer());
    }
    
    public Map<String, Object> getLearningProgress() {
        Map<String, Object> progress = new HashMap<>();
        
        // 获取学习统计数据
        Map<String, Object> stats = questionService.getStatistics();
        progress.put("statistics", stats);
        
        // 获取最近5个学习的主题
        List<String> recentTopics = learningPathRepository.findRecentTopics(PageRequest.of(0, 5));
        progress.put("recentTopics", recentTopics);
        
        // 计算学习趋势
        Map<String, Long> learningTrend = calculateLearningTrend();
        progress.put("trend", learningTrend);
        
        return progress;
    }
    
    public LearningPath getLearningPath(Long id) {
        return learningPathRepository.findById(id)
            .orElseThrow(() -> new RuntimeException("Learning path not found"));
    }
    
    private Map<String, Long> calculateLearningTrend() {
        Map<String, Long> trend = new HashMap<>();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime weekAgo = now.minusWeeks(1);
        
        // 获取每天的学习数据
        List<Question> recentQuestions = questionService.getQuestionsByDateRange(weekAgo, now);
        
        // 按日期分组统计
        Map<LocalDate, Long> dailyStats = recentQuestions.stream()
            .collect(Collectors.groupingBy(
                q -> q.getCreateTime().toLocalDate(),
                Collectors.counting()
            ));
        
        // 填充结果
        for (int i = 0; i < 7; i++) {
            LocalDate date = now.minusDays(i).toLocalDate();
            trend.put(date.toString(), dailyStats.getOrDefault(date, 0L));
        }
        
        return trend;
    }
} 